package com.seejoke.sharding.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seejoke.sharding.entity.User;
import com.seejoke.sharding.service.UserService;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author yangzhongying
 * @date 2020/5/14 13:38
 * @see com.seejoke.sharding.controller.UserController
 */
@RestController
public class UserController {
  private static final Logger logger = LoggerFactory.getLogger(UserController.class);

  @Resource private UserService userService;

  @GetMapping("/insert")
  public String test() {
    // 测试新增100条数据  根据id策略分布到各库
    for (int i = 0; i < 100; i++) {
      User user = new User();
      user.setSex(new Random().nextInt(2));
      user.setUserName("测试" + i);
      user.setCreateTime(new Date());
      this.userService.save(user);
    }
    return "ok";
  }

  @GetMapping("/query/{id}")
  public String query(@PathVariable("id") Long id) {
    // 根据id查询用户信息
    User user = this.userService.getById(id);
    logger.info("用户信息:{}", user);
    return JSON.toJSONString(user);
  }

  @GetMapping("/delete/{id}")
  public String delete(@PathVariable("id") Long id) {
    // 根据id查询用户信息
    boolean result = this.userService.removeById(id);
    logger.info("删除结果:{}", result);
    return "ok";
  }

  @GetMapping("/list")
  public String list() {
    // 查询列表
    List<User> lists = this.userService.list();
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("total", lists != null ? lists.size() : 0);
    jsonObject.put("list", lists);
    return jsonObject.toJSONString();
  }
}
